package net.qqxh.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.qqxh.controller.common.FileViewRouter;
import net.qqxh.persistent.FileNode;
import net.qqxh.persistent.JfUserSimple;
import net.qqxh.persistent.Jfile;
import net.qqxh.persistent.SearchLib;
import net.qqxh.service.FileEsService;
import net.qqxh.service.FileService;
import net.qqxh.service.model.ResolveCallBackMsg;
import net.qqxh.service.task.FileResolveTaskCallBack;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author jason
 */
@Controller
public class FileController extends BaseController {
    @Autowired
    private FileService fileService;
    @Autowired
    private FileEsService fileEsService;
    @ResponseBody
    @RequestMapping("/resolve")
    public Object resolve() throws IOException {
        JfUserSimple jfUserSimple = getLoginUser();
        if (jfUserSimple == null) {
            return responseJsonFactory.getSuccessJson("请登陆", "");
        }
        fileService.resolveAllFile(jfUserSimple.getSearchLib(), msg -> {
        });
        return "success";
    }

    @ResponseBody
    @RequestMapping("/search")
    public Object get(@RequestParam(name = "keyword") String keyword, @RequestParam(name = "path") String path,
                      @RequestParam(name = "es_from", defaultValue = "0") Integer esFrom,
                      @RequestParam(name = "es_size", defaultValue = "50") Integer esSize) throws IOException {
        List<Map> list = new ArrayList<>();
        try {
            JfUserSimple jfUserSimple = getLoginUser();
            if (jfUserSimple == null) {
                return responseJsonFactory.getSuccessJson("请登陆", "");
            }
            if (StringUtils.isNotEmpty(keyword)) {
                list = fileService.queryFileFromES(jfUserSimple.getSearchLib().getEsIndex(), keyword, path, esFrom, esSize);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return responseJsonFactory.getErrorJson("查询数据失败", null);
        }
        return responseJsonFactory.getSuccessJson("查询数据成功", list);
    }

    @RequestMapping("/show")
    public String show(@RequestParam(name = "rid") String rid, ModelMap map) throws UnsupportedEncodingException {
        JfUserSimple jfUserSimple = getLoginUser();
        if (jfUserSimple == null) {
            return FileViewRouter.router("noview");
        }
        Jfile jfile = fileEsService.queryJfileByRid(jfUserSimple.getSearchLib(),rid);
        String filename = jfile.getViewName();
        map.addAttribute("fileUrl", "/load/" + URLEncoder.encode(filename, "UTF-8") + "?viewPath=" + URLEncoder.encode(jfile.getViewPath(), "UTF-8"));
        return FileViewRouter.router(filename.substring(filename.lastIndexOf(".") + 1, filename.length()));
    }

    @RequestMapping("/showbypath")
    public String showbypath(@RequestParam(name = "path") String path, ModelMap map) {
        try {
            JfUserSimple jfUserSimple = getLoginUser();
            if (jfUserSimple == null) {
                return FileViewRouter.router("noview");
            }
            List<Jfile> list = fileEsService.findFileByPath(jfUserSimple.getSearchLib(), path);
            Jfile jfile = list.get(0);
            String viewFix=jfile.getViewFix();
            String filename = jfile.getName()+(StringUtils.isEmpty(viewFix)?"":"."+jfile.getViewFix());
            map.addAttribute("fileUrl", "/load/" + URLEncoder.encode(filename, "UTF-8") + "?viewPath=" + URLEncoder.encode(jfile.getViewPath(), "UTF-8"));
            return FileViewRouter.router(filename.substring(filename.lastIndexOf(".") + 1));
        } catch (Exception e) {
            return FileViewRouter.router("noview");
        }
    }

    @ResponseBody
    @RequestMapping("/list")
    public Object list(@RequestParam(name = "path") String path, ModelMap map, HttpServletRequest request) {
        try {
            JfUserSimple jfUserSimple = getLoginUser();
            if(StringUtils.equals("root",path)){
                path=jfUserSimple.getSearchLib().getFileSourceDir();
            }
            Collection<File> collection = FileUtils.listFiles(new File(path), null, false);
            JSONObject result =new JSONObject();
            JSONArray jsonArray=new JSONArray();
            for (File f:collection){
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("thumbURL","/showbypath?path="+f.getPath());
                jsonObject.put("oriURL","/showbypath?path="+f.getPath());
                jsonObject.put("width",258);
                jsonObject.put("height",258);
                jsonObject.put("name",f.getName());
                jsonArray.add(jsonObject);
            }
            result.put("items",jsonArray);
            result.put("status","200");
            result.put("message","成功");
            result.put("count",collection.size());
            return result;
        } catch (Exception e) {
            return responseJsonFactory.getErrorJson("失败", "");
        }
    }

    @ResponseBody
    @RequestMapping("/upload")
    public Object upload(@RequestParam(name = "path") String path, ModelMap map, HttpServletRequest request) {
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            SearchLib  searchLib= getSearchLib();
            if(!StringUtils.equals(searchLib.getRemoteRepositoryMode(),"none")){
                return responseJsonFactory.getErrorJson("启用远程仓库模式，不允许本地管理", "");
            }
            MultipartFile multipartFile = multipartRequest.getFile("src");

            if (!path.endsWith(File.separator)) {
                path += File.separator;
            }
            String srcpath = path + multipartFile.getOriginalFilename();
            File file=new File(srcpath);
            FileUtils.writeByteArrayToFile(file, multipartFile.getBytes());
            FileNode fileNode = new FileNode(file );
            fileService.addNode2cache(fileNode,searchLib);
            fileService.resolveFileByPath(searchLib, path, null);
            return responseJsonFactory.getSuccessJson("成功", fileNode);
        } catch (Exception e) {
            return responseJsonFactory.getErrorJson("失败", "");
        }
    }
    @ResponseBody
    @RequestMapping("/addfolder")
    public Object addfolder(@RequestParam(name = "path") String path, @RequestParam(name = "folder") String folder,ModelMap map, HttpServletRequest request) {
        try {
            SearchLib  searchLib= getSearchLib();
            if(!StringUtils.equals(searchLib.getRemoteRepositoryMode(),"none")){
                return responseJsonFactory.getErrorJson("启用远程仓库模式，不允许本地管理", "");
            }
            if (!path.endsWith(File.separator)) {
                path += File.separator;
            }
            String newFolder= path+folder;
            File fd=new File(newFolder);
            if(!fd.exists()){
                fd.mkdirs();
                FileNode fileNode = new FileNode(fd );
                fileService.addNode2cache(fileNode,searchLib);
                return responseJsonFactory.getSuccessJson("成功", "");
            }
            return responseJsonFactory.getSuccessJson("文件夹已存在，无需再次创建", "");
        } catch (Exception e) {
            e.printStackTrace();
            return responseJsonFactory.getErrorJson("失败", "");
        }
    }

    @ResponseBody
    @RequestMapping("/sendToDesktop")
    public Object sendToDesktop(@RequestParam(name = "path") String path) {
        try {
            JfUserSimple jfUserSimple = getLoginUser();
            if (jfUserSimple == null) {
                return responseJsonFactory.getErrorJson("请登陆后再操作", "");
            }
            fileService.sendToDesktop(jfUserSimple.getSearchLib(), path, jfUserSimple.getUserid());
            return responseJsonFactory.getSuccessJson("成功发送到桌面", "");
        } catch (Exception e) {
            return responseJsonFactory.getErrorJson("操作失败，请联系管理员", "");
        }
    }

    @ResponseBody
    @RequestMapping("/removeFromDesktop")
    public Object removeFromDesktop(@RequestParam(name = "path") String path) {
        try {
            JfUserSimple jfUserSimple = getLoginUser();
            if (jfUserSimple == null) {
                return responseJsonFactory.getErrorJson("请登陆后再操作", "");
            }
            fileService.removeFromDesktop(jfUserSimple.getSearchLib(), path, jfUserSimple.getUserid());
            return responseJsonFactory.getSuccessJson("删除成功", "");
        } catch (Exception e) {
            return responseJsonFactory.getErrorJson("操作失败，请联系管理员", "");
        }
    }

    @ResponseBody
    @RequestMapping("/getMyDesktop")
    public Object getMyDesktop() {
        List list = new ArrayList();
        try {
            JfUserSimple jfUserSimple = getLoginUser();
            if (jfUserSimple == null) {
                return responseJsonFactory.getSuccessJson("获取数据成功", list);
            }
            list = fileService.getMyDesktop(jfUserSimple.getUserid());
            return responseJsonFactory.getSuccessJson("获取数据成功", list);
        } catch (Exception e) {
            return responseJsonFactory.getErrorJson("获取数据失败", "");
        }
    }

    @ResponseBody
    @RequestMapping("/clearDesktop")
    public Object clearDesktop() {

        try {
            JfUserSimple jfUserSimple = getLoginUser();
            if (jfUserSimple == null) {
                return responseJsonFactory.getSuccessJson("请登陆", "");
            }
            fileService.clearDesktop(jfUserSimple.getUserid());
            return responseJsonFactory.getSuccessJson("清理成功", "");
        } catch (Exception e) {
            return responseJsonFactory.getErrorJson("清理失败", "");
        }
    }

    @RequestMapping("/load/{filename}")
    public Object load(@RequestParam(name = "viewPath") String viewPath, @PathVariable(name = "filename") String filename, HttpServletResponse res) {
        File file = new File(viewPath);
        OutputStream os = null;
        try {
            res.setCharacterEncoding("utf-8");
            os = res.getOutputStream();
            IOUtils.copy(new FileInputStream(file), os);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
        return null;
    }

    @RequestMapping("/loadImg")
    public Object loadImg(@RequestParam(name = "path") String path, HttpServletResponse res) {
        File file = new File(path);
        OutputStream os = null;
        try {

            os = res.getOutputStream();
            IOUtils.copy(new FileInputStream(file), os);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
        return null;
    }

    @RequestMapping("/downloadFile")
    public Object downloadFile(@RequestParam(name = "path") String path, HttpServletResponse res) {
        File file = new File(path);

        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            res.setHeader("content-type", "application/octet-stream");
            res.setContentType("application/octet-stream");
            res.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes(), "iso-8859-1"));
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @ResponseBody
    @RequestMapping("/resolvebypath")
    public Object resolvebypath(@RequestParam(name = "path") String path, ModelMap map) {
        try {
            JfUserSimple jfUserSimple = getLoginUser();
            if (jfUserSimple == null) {
                return   responseJsonFactory.getSuccessJson("请登陆", "");
            }
            fileService.resolveFileByPath(jfUserSimple.getSearchLib(), path, null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseJsonFactory.getSuccessJson("后台正在转换中", "");

    }




    @ResponseBody
    @RequestMapping("/refreshCache")
    public Object refreshCache() {
        try {
            fileService.resolveFliesList2TreeNode();
        } catch (Exception e) {
            return responseJsonFactory.getErrorJson("刷新缓存失败", null);
        }
        return responseJsonFactory.getSuccessJson("刷新缓存成功", null);
    }




    @ResponseBody
    @RequestMapping("/readFile2FormatTree")
    public Object readFile2FormatTree() {
        JfUserSimple jfUserSimple = getLoginUser();
        if (jfUserSimple == null) {
            return responseJsonFactory.getSuccessJson("请登陆", "");
        }
        return fileService.readFile2FormatTree(jfUserSimple.getSearchLib().getFileSourceDir());
    }


    @ResponseBody
    @RequestMapping("/loadUserSetting")
    public Object loadUserSetting() {
        JfUserSimple jfUserSimple = getLoginUser();
        if (jfUserSimple == null) {
            return responseJsonFactory.getErrorJson("请登陆", "");
        }
        return  responseJsonFactory.getSuccessJson("获取成功",jfUserSimple.getSearchLib());
    }
}
